using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Media.Media3D;
using HalconDotNet;

namespace 通用车牌识别联合编程
{
    public partial class Form1 : Form
    {
        HObject ho_Image, ho_GrayImage, ho_Region;
        HObject ho_ConnectedRegions, ho_SelectedRegions, ho_RegionFillUp;
        HObject ho_RegionTrans, ho_ImageReduced, ho_ImageAffineTrans1;
        HImage image;


        HObject ho_ImageAffineTrans, ho_RegionAffineTrans, ho_ImageReduced1;
        // Local control variables 
        HTuple hv_Area = new HTuple(), hv_Row = new HTuple();
        HTuple hv_Column = new HTuple(), hv_Phi = new HTuple();
        HTuple hv_HomMat2D = new HTuple();
        public Form1()
        {
            InitializeComponent();
            hswcCar.MouseWheel += (sender, e) =>
            {
                hswcCar.HSmartWindowControl_MouseWheel(sender, e);
            };

            hswcCarROI.MouseWheel += (sender, e) =>
            {
                hswcCarROI.HSmartWindowControl_MouseWheel(sender, e);
            };
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "所有图片|*.bmp;*.jpg";
            openFileDialog.Title = "加载图片";
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //ho_Image = new HImage(openFileDialog.FileName);
                image = new HImage(openFileDialog.FileName);
                //hswcCar.HalconWindow.DispObj(ho_Image);
                hswcCar.HalconWindow.DispImage(image);

                hswcCar.SetFullImagePart();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            HOperatorSet.TextLineOrientation(image, image, 50, -50 * Math.PI / 180, 50 * Math.PI / 180, out HTuple angle);

            double phi = angle;

            //Console.WriteLine($"弧度：{phi}");
            HImage rotageImage = image.RotateImage(-phi / 3.14 * 180, "constant");

            HImage ImageEmphasize = rotageImage.Emphasize(7, 7, 1);

            HImage ImageMedian = rotageImage.MedianImage("circle", 5, "mirrored");
            //获取3个通道

            HImage redImage = ImageEmphasize.Decompose3(out HImage greenImage, out HImage blueImage);

            HImage HImage = redImage.TransFromRgb(greenImage, blueImage, out HImage SImage, out HImage VImage, "hsv");


            HRegion region = SImage.BinaryThreshold("max_separability", "light", out HTuple usedThreshold);

            HRegion RegionOpening = region.OpeningCircle(2D);

            HRegion ConnectedRegions = RegionOpening.Connection();

            HRegion SelectedRegions = ConnectedRegions.SelectShape("area", "and", 32000D, 350000).SelectShape("rectangularity", "and", 0.4, 1).SelectShape("row", "and", 0, 2780);

            HRegion RegionDilation1 = SelectedRegions.DilationCircle(8D);

            HRegion RegionFillUp1 = RegionDilation1.FillUp();

            HRegion RegionUnion1 = RegionFillUp1.Union1();

            HRegion ConnectedRegions2 = RegionUnion1.Connection();

            HRegion RegionTrans2 = ConnectedRegions2.ShapeTrans("rectangle2");

            int Number = RegionTrans2.CountObj();

            HOperatorSet.GenEmptyObj(out HObject ROI);

            for (int i = 1; i <= Number; i++)
            {
                HRegion ObjectSelected = RegionTrans2.SelectObj(i);

                double changZhou = ObjectSelected.RegionFeatures("rect2_len1");

                double duanZhou = ObjectSelected.RegionFeatures("rect2_len2");

                double value = changZhou / duanZhou;

                if (value > 2.8 && value < 4.3)
                {
                    ROI = ROI.ConcatObj(ObjectSelected);
                }
            }
            //读取ROI的个数
            int Number1 = ROI.CountObj();
            if (Number1 == 1)
            {
                HRegion hRegionROI = new HRegion(ROI);

                HRegion RegionErosion = hRegionROI.ErosionRectangle1(80, 80);

                HImage ImageReduced = ImageMedian.ReduceDomain(RegionErosion);

                HRegion Region1 = ImageReduced.BinaryThreshold("max_separability", "light", out HTuple usedThreshold1);
                HRegion ConnectedRegions1 = Region1.Connection();
                HRegion SelectedRegions1 = ConnectedRegions1.SelectShape("contlength", "and", 105, 150000).SelectShape("area", "and", 500, 100000);

                HRegion RegionDialation = SelectedRegions1.DilationCircle(8d);

                HRegion RegionUnion = RegionDialation.Union1();

                HRegion ConnectedRegion3 = RegionUnion.Connection();

                HRegion RegionIntersection = ConnectedRegion3.Intersection(SelectedRegions1);

                HRegion SortedRegions = RegionIntersection.SortRegion("character", "true", "row");

                HOCRMlp mlp = new HOCRMlp();

                mlp.ReadOcrClassMlp("charact.omc");
                //进行OCR识别
                HTuple carNo = mlp.DoOcrMultiClassMlp(SortedRegions, ImageReduced, out HTuple con);

                txtNum.Text = string.Join("", carNo);


                this.hswcCar.HalconWindow.ClearWindow();

                this.hswcCarROI.HalconWindow.ClearWindow();

                hswcCar.HalconWindow.SetColor("pink");

                this.hswcCar.HalconWindow.DispObj(image);

                this.hswcCar.SetFullImagePart();

                this.hswcCarROI.HalconWindow.DispObj(ImageReduced);

                this.hswcCarROI.SetFullImagePart();
                // 获取ROI区域的外接矩形坐标
                HTuple row1, column1, row2, column2;
                HOperatorSet.SmallestRectangle1(ImageReduced, out row1, out column1, out row2, out column2);

                // 计算显示区域中心点和大小
                double centerRow = (row1.D + row2.D) / 2.0;
                double centerCol = (column1.D + column2.D) / 2.0;
                double height = row2.D - row1.D;
                double width = column2.D - column1.D;

                // 设置窗口显示区域（扩大1.5倍区域以便更好查看）
                double zoomFactor = 1.5;
                HOperatorSet.SetPart(hswcCarROI.HalconWindow,
                                    centerRow - height * zoomFactor / 2.0,
                                    centerCol - width * zoomFactor / 2.0,
                                    centerRow + height * zoomFactor / 2.0,
                                    centerCol + width * zoomFactor / 2.0);
            }
            else
            {

                HRegion ROI1 = new HRegion(ROI);
                HRegion ROI2 = ROI1.SelectShape("area", "and", 110000d, 340000);

                HRegion RegionErosion = ROI2.ErosionRectangle1(80, 120);

                HImage ImageReduced = ImageMedian.ReduceDomain(RegionErosion);

                HRegion Region1 = ImageReduced.BinaryThreshold("max_separability", "light", out HTuple usedThreshold1);


                HRegion ConnectedRegions1 = Region1.Connection();

                HRegion SelectedRegions1 = ConnectedRegions1.SelectShape("contlength", "and", 105, 150000).SelectShape("area", "and", 600, 100000);

                HRegion RegionDilation = SelectedRegions1.DilationCircle(8.0);

                HRegion RegionUnion = RegionDilation.Union1();

                HRegion ConnectedRegions3 = RegionUnion.Connection();

                HRegion RegionIntersection = ConnectedRegions3.Intersection(SelectedRegions1);

                HRegion SortedRegions = RegionIntersection.SortRegion("character", "true", "row");

                HOCRMlp mlp = new HOCRMlp();

                mlp.ReadOcrClassMlp("charact.omc");

                HTuple carNo = mlp.DoOcrMultiClassMlp(SortedRegions, ImageReduced, out HTuple con);

                txtNum.Text = string.Join("", carNo);

                this.hswcCar.HalconWindow.ClearWindow();

                this.hswcCarROI.HalconWindow.ClearWindow();

                hswcCar.HalconWindow.SetColor("pink");

                this.hswcCar.HalconWindow.DispObj(image);

                this.hswcCar.SetFullImagePart();

                this.hswcCarROI.HalconWindow.DispObj(ImageReduced);

                this.hswcCarROI.SetFullImagePart();
                // 获取ROI区域的外接矩形坐标
                HTuple row1, column1, row2, column2;
                HOperatorSet.SmallestRectangle1(ImageReduced, out row1, out column1, out row2, out column2);

                // 计算显示区域中心点和大小
                double centerRow = (row1.D + row2.D) / 2.0;
                double centerCol = (column1.D + column2.D) / 2.0;
                double height = row2.D - row1.D;
                double width = column2.D - column1.D;

                // 设置窗口显示区域（扩大1.5倍区域以便更好查看）
                double zoomFactor = 1.5;
                HOperatorSet.SetPart(hswcCarROI.HalconWindow,
                                    centerRow - height * zoomFactor / 2.0,
                                    centerCol - width * zoomFactor / 2.0,
                                    centerRow + height * zoomFactor / 2.0,
                                    centerCol + width * zoomFactor / 2.0);










            }











        }

  
    }
}
